import os
import re
import numpy as np

class Game(object):
    def __init__(self, file_path):
        self.N_players, self.N_actions, self.payoffs = self.parse_file(file_path)

    def parse_file(self, file_path):
        N_players = None
        N_actions = None
        payoffs = None

        with open(file_path, "r") as fp:
            lines = fp.readlines()
        lines = [line.strip() for line in lines]
        for line in lines:
            if line.startswith("Actions"):
                PATTERN = r"Actions:\s(\d+(?:\s+\d+)*)"
                actions_str = re.findall(PATTERN, line)[0]
                N_actions = [eval(i) for i in actions_str.split(" ")]
                N_players = len(N_actions)
                break
        else:
            PATTERN = r"\{\s(\d+(?:\s+\d+)*)\s\}"
            for line in lines:
                matches = re.findall(PATTERN, line)
                if len(matches) > 0:
                    actions_str = matches[0]
                    N_actions = [eval(i) for i in actions_str.split(" ")]
                    N_players = len(N_actions)
                    break
        
        PATTERN = "^(\d+(?:\s+-?\d+)*)"
        for line in lines[::-1]:
            matches = re.findall(PATTERN, line)
            if len(matches) > 0:
                payoffs = matches[0]
                break
        payoffs = np.asarray([eval(i) for i in payoffs.split()])
        payoffs = payoffs.reshape((*N_actions, N_players))
        
        assert (not N_players is None) and (not N_actions is None) and (not payoffs is None)
        return N_players, np.asarray(N_actions), payoffs


if __name__ == "__main__":
    for file in os.listdir("examples"):
        if file.endswith(".nfg"):
            g = Game(os.path.join("examples", file))
            print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
            print(g.N_players, g.N_actions, g.payoffs)
